<template>
	<view class="wper100 hper100 map">
		<view v-if="$validatenull(deviceData)">
			<cust-empty desc="暂无车辆,请前往绑定!" btnText="前往绑定" :showDefaultBtn="true"
				@clickBtn="$navigateTo('/pagesMy/views/addDevice')">
			</cust-empty>
		</view>
		<!-- <view v-else-if="deviceData.isAuth == '1'">
			<cust-empty desc="当前车辆未认证" btnText="前往认证" :showDefaultBtn="true" @clickBtn="gotoAuth(deviceData)">
			</cust-empty>
		</view> -->
		<view v-else style="width: 100%; height: 100%;">
			<map :enable-satellite="enableSatellite" style="width: 100%; height: 100%;" v-if="longitude !=-1"
				:show-location="true" :latitude="latitude" :longitude="longitude" :circles="circles" :markers="markers"
				:enable-rotate="false" :scale="13" id='map'>
			</map>
			<!-- 左上角悬浮 -->
			<!-- <view class="card-cell-box p30" style="position: absolute;top:15px;left:15px;">
				<view class="f30">
					{{deviceData.nickName}}
				</view>
			</view> -->
			<!-- 右上角悬浮 -->
			<view class="right-operate">
				<view class="item flex-column-center mt0" @click="gotoUserLocation">
					<u-icon color="#00FFBC" customPrefix="iconfontbike iconbike" name="xiaomotuochexiaodianche"
						:isShowIcon="false" v-if="locationMode == 'my'"></u-icon>
					<u-icon color="#00FFBC" name="account" v-else>
					</u-icon>
					<text class="mt10">{{locationMode == 'car' ? '我的' : '车辆'}}</text>
				</view>
				<view class="item flex-column-center" @click="trace">
					<u-icon :color="isRealTime ? '#00FFBC' : '#B3B3B3'" customPrefix="iconfontbike iconbike"
						name="a-yundanzhuizong-yimidida-011" :isShowIcon="false"></u-icon>
					<text class="mt10">追踪</text>
				</view>
				<view class="item flex-column-center" @click="enableSatelliteFun">
					<u-icon :color="enableSatellite ? '#B3B3B3' : '#00FFBC'" customPrefix="iconfontbike iconbike"
						name="a-jingtouqiehuan2" :isShowIcon="false"></u-icon>
					<text class="mt10">视图</text>
				</view>
			</view>
			<!-- 悬浮操作 -->
			<view class="border-operate-wrapper">
				<view class="plr30">
					<!-- 操作栏 -->
					<view class="border-operate" v-if="mapMode !='fense' && !fenseVisible">
						<view class="flex-align-center">
							<view class="flex-column-center" style="width: 80px;" v-if="mapMode == 'map'">
								<image
									:src="deviceData.carPhotoLink ? deviceData.carPhotoLink  : '/static/images/index/bike.png'"
									style="width:50px;height:50px"></image>
								<text class="f20 mt10">{{deviceData.licensePlateNumber}}</text>
							</view>
							<view class="flex-column ml20 flex1">
								<view class="flex-row flex-between">
									<view class="flex-row">
										<text class="f24">{{address}}</text>
										<view class="flex-row ml20 flex-align-center" style="width:110px" v-if="mapMode == 'map'">
											<u-icon :size="10" name="a-shijian2" :isShowIcon="false" color="#B3B3B3"
												customPrefix="iconfontbike iconbike"></u-icon>
											<text class="f20" style="color:#B3B3B3">{{time}}</text>
											<view v-if="mapMode!='location'" @click="refresh" style="padding: 5px;"
												:class="[isRefresh?'refresh':'']">
												<u-icon :size="10" name="a-shuaxin5" :isShowIcon="false" color="#B3B3B3"
													customPrefix="iconfontbike iconbike"></u-icon>
											</view>

										</view>
									</view>
									<u-icon name="a-daohang2" @click="navigation" :isShowIcon="false" color="#00FFBC"
										customPrefix="iconfontbike iconbike"></u-icon>
								</view>
								<view class="flex-align-start flex-row mt10">
									<u-icon name="map" color="#B3B3B3" size="12" style="position: relative;top:6upx">
									</u-icon>
									<text class="f20 ml10" style="color:#B3B3B3">{{recommend}}</text>
								</view>
							</view>
						</view>
						<view v-if="mapMode =='map'" class="flex-align-space-around pt30 mt30"
							style="border-top:1px solid #C9D3E9" @click="openFenseVisible">
							<view class="flex-column-center">
								<u-icon customPrefix="iconfontbike iconbike" name="a-weilandianziweilancunzhuang1"
									:isShowIcon="false"></u-icon>
								<text>围栏</text>
							</view>
						</view>
					</view>
					<!-- 操作栏 -->
					<!-- 电子围栏 -->
					<view class="border-operate" v-if="mapMode =='fense' || fenseVisible">
						<view class="flex-between">
							<view class="flex-align-center">
								<text class="f30 mr10">电子围栏</text>
								<text style="color: #B2B2B2;">车辆离开电子围栏，将提醒你</text>
							</view>
							<view @click="closeFenseVisible" style="padding: 10px;" v-if="mapMode !='fense'">
								<u-icon color="#B2B2B2" name="close" :size="12"></u-icon>
							</view>

						</view>

						<view class="flex-between mt40">
							<text>围栏中心</text>
							<!-- 开启围栏 -->
							<text v-if="$validatenull(deviceData.carElectronicFence)">{{address}}</text>
							<!-- 关闭围栏描述不应该变化 -->
							<text v-else>{{closeFenseAddress}}</text>
						</view>
						<view class="flex-between mt10">
							<text>围栏半径</text>
							<view class="flex-row">
								<text @click="subtract" class="f30" style="padding: 10px;"
									v-if="$validatenull(deviceData.carElectronicFence) && raduis>1">-</text>
								<view style="width: 50px;text-align: center;padding: 13px;10px">
									<text>{{raduis}}</text>
									<text>km</text>
								</view>
								<text @click="addRaduis" class="f30" style="padding: 10px;"
									v-if="$validatenull(deviceData.carElectronicFence) && raduis<30">+</text>
							</view>
						</view>
						<view class="flex-between mt10">
							<text>开启电子围栏</text>
							<view class="flex-row">
								<u-switch v-model="fenseStatus" @change="changeFense" :disabled="fenseSwicthDisable">
								</u-switch>
							</view>
						</view>
						<!-- <view class="flex-center mini-button">
							<view class="mt60 w300 ">
								<u-button size="normal" :throttleTime="1000" @click="operateFense" iconColor="#0C1124"
									customPrefix="iconfontbike iconbike" icon="a-weilandianziweilancunzhuang1"
									type="primary" :text="$validatenull(deviceData.carElectronicFence)? '开启围栏':'关闭围栏'">
								</u-button>
							</view> -->
					</view>
				</view>
				<!-- 电子围栏 -->
			</view>
		</view>
	</view>
	<!-- 悬浮操作 -->
	</view>

</template>

<script>
	import custEmpty from "@/components/cust-empty/index.vue";
	import {
		getCarDetailAPI,
		verifyCarAPI
	} from "@/api/api/car.js"
	import {
		saveFenceAPI,
		closeFenceAPI,
	} from "@/api/api/map.js"
	import {
		throttle,
		timeago,
		reverseGeocoderToAddress,
		getDifferenceDay
	} from '@/utils/utils.js'
	let qqmapsdk;
	let timerId = '';
	let refreshTimeAddress = new Date().getTime();
	let markerTime = new Date().getTime();
	let dateTimeStamp = '';
	import {
		mapState
	} from 'vuex'
	import {
		getStoreSyncUtil
	} from "@/utils/store.js"
	export default {
		components: {
			custEmpty
		},
		data() {
			return {
				isRefresh: false,
				fenseVisible: false,
				//中心点定位
				latitude: -1,
				longitude: -1,
				address: '-',
				closeFenseAddress: "-",
				recommend: '-',
				time: '-',
				markers: [{}],
				isRealTime: true,
				//是否开启卫星图
				enableSatellite: false,
				raduis: 1,
				circles: [{}],
				isHasModal: false,
				isFirstLoad: true,
				fenseStatus: false,
				fenseSwicthDisable: false,
				mapMode:'map',
				locationMode: 'car', //my 我的 //car 车辆
			}
		},

		computed: {
			...mapState(["unReadNum", "deviceData", "mapDataPoint","isProduct"])
		},
		onShow() {
			
			this.fenseStatus = this.$validatenull(this.deviceData.carElectronicFence) ? false : true
			this.updateMark();
			this.updateFense();
			if(this.isProduct){
				this.gotoAuthDialog();
			}
			this.gotoSubscribeDialog();
			this.$store.commit("setSpecialAppOnShow", false);
			if (this.unReadNum == 0) {
				uni.removeTabBarBadge({
					index: 3,
				})
			} else {
				uni.setTabBarBadge({
					index: 3,
					text: this.unReadNum + ''
				})
			}
			if (!this.$validatenull(this.mapDataPoint)) {
				let mapContext = uni.createMapContext("map");
				mapContext.moveToLocation({
					longitude: Number(this.mapDataPoint.carLongitude),
					latitude: Number(this.mapDataPoint.carLatitude)

				});
			}
			// this.longitude = Number(this.mapDataPoint.carLongitude)
			// this.latitude = Number(this.mapDataPoint.carLatitude)
		},
		watch: {
			"unReadNum": {
				handler(unReadNum) {
					if (this.unReadNum == 0) {
						uni.removeTabBarBadge({
							index: 3,
						})
					} else {
						uni.setTabBarBadge({
							index: 3,
							text: this.unReadNum + ''
						})
					}
				}
			}
		},
		watch: {
			"mapDataPoint": {
				handler(mqttData) {
					if (!this.$validatenull(mqttData)) {

						if (mqttData.upDataType == 0) {
							let circles = this.circles[0];
							if (!this.$validatenull(this.deviceData.carElectronicFence)) {
								if (mqttData.isCrossFence == 1) {
									this.$set(this.circles, 0, {
										...circles,
										fillColor: '#EC101033',
										color: '#EC1010FF',
										strokeWidth: 1
									})
								} else {
									this.$set(this.circles, 0, {
										...circles,
										fillColor: '#06B7F333',
										color: '#06B7F3FF',
										strokeWidth: 1
									})
								}
							}

						} else {
							//实时更新车的定位信息,定位发生改变的时候才实时更新数据
							if (this.isRealTime) {
								if (!this.$validatenull(mqttData.carLatitude) && !this.$validatenull(mqttData
										.carLongitude)) {
									if (this.markers[0].latitude != mqttData.carLatitude || this.markers[0]
										.longitude != mqttData.carLongitude) {
										this.$set(this.markers, 0, {
											id: 1,
											width: 20,
											height: 20, //要设置宽高，不然无法显示
											latitude: Number(mqttData.carLatitude),
											longitude: Number(mqttData.carLongitude),
											iconPath: '/static/images/index/bike-people.png',
										})

										if (new Date().getTime() - refreshTimeAddress > 5 * 1000) {
											this.getAddressDesc();
											refreshTimeAddress = new Date().getTime();
										}
									}
								}
							}
						}
					}
				},
				deep: true,
			}

		},
		methods: {
			gotoAuthDialog() {
				if (this.deviceData.isAuth == "1" && !this.isHasModal) {
					let that = this;
					this.isHasModal = true;
					uni.showModal({
						title: '提示',
						content: "当前车辆未认证,如已认证,请5分钟后重新进入小程序",
						showCancel: true,
						cancelText: "退出",
						confirmText: "去认证",
						success(res) {
							if (res.confirm) {
								that.isHasModal = false;
								that.$navigateTo("/pagesMy/views/myMotorbike");
							} else if (res.cancel) {
								that.isHasModal = false;
								wx.exitMiniProgram({
									success(res) {
										console.log(JSON.stringify(res));
									},
									fail(res) {
										console.log(`exitMiniProgram fail: ${JSON.stringify(res)}`);
									}
								});
							}
						}
					});
				}
			},
			gotoSubscribeDialog() {
				if (!this.$validatenull(this.deviceData.tboxExpireTime) && !this.isHasModal) {
					let that = this;
					this.isHasModal = true;
					let differenceDay = getDifferenceDay(this.deviceData.tboxExpireTime);
					if (differenceDay < 0) {
						uni.showModal({
							title: '提示',
							content: "当前服务已到期，请前往-我的-服务订阅进行订阅",
							showCancel: true,
							cancelText: "退出",
							confirmText: "去订阅",
							success(res) {
								if (res.confirm) {
									that.isHasModal = false;
									that.$switchTab("/pages/views/home/userConfig");
								} else if (res.cancel) {
									that.isHasModal = false;
									wx.exitMiniProgram({
										success(res) {
											console.log(JSON.stringify(res));
										},
										fail(res) {
											console.log(`exitMiniProgram fail: ${JSON.stringify(res)}`);
										}
									});
								}
							}
						});
					}
				}
			},
			//去认证
			gotoAuth(item) {
				this.$store.commit("setSpecialAppOnShow", true);
				if (item.isAuth == "1") {
					verifyCarAPI(item.id).then(([err, data]) => {
						if (err) return;
						let resData = JSON.parse(data);
						this.$store.commit("setVerifyUrl", resData.url)
						this.$reLaunch(`/pages/views/home/verify`)
					})
				}
			},
			$switchTab(url) {
				uni.switchTab({
					url: url
				});
			},
			//导航
			navigation: throttle(function() {
				this.$store.commit("setSpecialAppOnShow", true);
				uni.openLocation({
					latitude: this.markers[0].latitude,
					longitude: this.markers[0].longitude,
					success: function() {}
				});
			}),
			enableSatelliteFun: throttle(function() {
				this.enableSatellite = !this.enableSatellite;
				if (this.enableSatellite) {
					this.$showToast('打开卫星视图');
				} else {
					this.$showToast('关闭卫星视图');
				}
			}),
			trace: throttle(function() {
				this.isRealTime = !this.isRealTime;
				if (this.isRealTime) {
					this.$showToast('打开追踪模式');
				} else {
					this.$showToast('关闭追踪模式');
				}
			}),
			//更新地图中心点
			gotoUserLocation: throttle(function() {
				let that = this;
				console.log("===", this.locationMode)
				if (this.locationMode == "car") {
					uni.getLocation({
						type: 'gcj02',
						success: function(res) {
							console.log("res", res);
							that.longitude = res.longitude;
							that.latitude = res.latitude;
						},
						fail: function(res) {
							console.log("res", res)
						}
					});
					this.locationMode = "my";
				} else {
					that.longitude = Number(this.mapDataPoint.carLongitude)
					that.latitude = Number(this.mapDataPoint.carLatitude)
					this.locationMode = "car";
				}



			}),
			// changeFense() {
			// 	console.log("操作围栏");
			// 	this.fenseSwicthDisable = true;
			// 	setTimeout(()=>{ //报错的情况没有重设
			// 		this.fenseSwicthDisable = false;
			// 	},500)
			// 	if (this.$validatenull(this.deviceData.carElectronicFence)) {
			// 		this.saveFenceFun()
			// 	} else {
			// 		this.closeFenceFun();
			// 	}
			// },
			changeFense: throttle(function() {
				console.log("操作围栏");
				this.fenseSwicthDisable = true;
				setTimeout(() => { //报错的情况没有重设
					this.fenseSwicthDisable = false;
				}, 1000)
				if (this.$validatenull(this.deviceData.carElectronicFence)) {
					this.saveFenceFun()
				} else {
					this.closeFenceFun();
				}
			}),
			operateFense: throttle(function() {
				console.log("操作围栏");
				if (this.$validatenull(this.deviceData.carElectronicFence)) {
					this.saveFenceFun()
				} else {
					this.closeFenceFun();
				}
			}),
			refresh: throttle(function() {
				this.isRefresh = true;
				setTimeout(() => {
					this.isRefresh = false;
				}, 1000)
				this.updateMark();

			}),
			//更新围栏信息
			updateFense() {
				if (!this.$validatenull(this.deviceData.carElectronicFence)) {
					let fense = this.deviceData.carElectronicFence;
					this.raduis = fense.radius / 1000;
					let color = this.mapDataPoint.isCrossFence == 1 ? '#EC1010FF' : '#06B7F3FF';
					let fillColor = this.mapDataPoint.isCrossFence == 1 ? '#EC101033' : '#06B7F333';
					this.$set(this.circles, 0, {
						radius: fense.radius,
						latitude: fense.latitude,
						longitude: fense.longitude,
						fillColor: fillColor,
						color: color,
						strokeWidth: 1
					})
					reverseGeocoderToAddress(fense.latitude, fense.longitude, (res) => {
						this.closeFenseAddress = res.result.address;
					})

				} else {
					this.$set(this.circles, 0, {
						radius: 1,
						longitude: -1,
						latitude: -1
					})
				}
			},
			//更新车子坐标点
			updateMark(callback = () => {}) {
				if (!this.$validatenull(this.mapDataPoint.carLatitude)) {
					//车的中心点
					this.latitude = Number(this.mapDataPoint.carLatitude);
					this.longitude = Number(this.mapDataPoint.carLongitude);
					this.$set(this.markers, 0, {
						id: 1,
						width: 20,
						height: 20, //要设置宽高，不然无法显示
						latitude: this.latitude,
						longitude: this.longitude,
						iconPath: '/static/images/index/bike-people.png',
						//iconPath: ''
					})
					this.getAddressDesc();
					callback();
				}
			},
			setTime() {
				dateTimeStamp = '';
				this.time = timeago(dateTimeStamp);
				dateTimeStamp = new Date().getTime();
				clearTimeout(timerId);
				timerId = setInterval(() => {
					this.time = timeago(dateTimeStamp)
				}, 20000)
			},
			getAddressDesc() {
				this.setTime();
				//如果存在经纬度，则解析经纬度
				if (!this.$validatenull(this.markers[0].longitude)) {
					//获取当前地图的视野范围,如果当前经纬度不在视野范围，则重置地图的中心点为当前定位
					reverseGeocoderToAddress(this.markers[0].latitude, this.markers[0].longitude, (res) => {
						this.address = res.result.address;
						this.recommend = this.$validatenull(res.result.formatted_addresses) ? res.result
							.address : res.result.formatted_addresses.recommend;
					});
				}
			},
			addRaduis() {
				if (this.raduis < 30) {
					this.raduis = this.raduis + 1;
				}
			},
			subtract() {
				if (this.raduis > 1) {
					this.raduis = this.raduis - 1;
				}
			},
			openFenseVisible: throttle(function() {
				this.radius = this.circles[0].radius;
				this.fenseVisible = true;
			}),
			closeFenseVisible: throttle(function() {
				console.log("222");
				this.fenseVisible = false;
			}),

			saveFenceFun() {
				let fenseLongitude;
				let fenseLatitude;
				let that = this;
				if (this.markers.length > 0) {
					fenseLongitude = this.markers[0].longitude;
					fenseLatitude = this.markers[0].latitude;
					this.saveFenceAPIFun(fenseLongitude, fenseLatitude);
				} else {
					if (this.longitude == -1) {
						let that = this;
						uni.getLocation({
							type: 'gcj02',
							success: function(res) {
								fenseLongitude = res.longitude;
								fenseLatitude = res.latitude;
								that.saveFenceAPIFun(fenseLongitude, fenseLatitude);
							},
							fail: function(res) {
								that.$showToast("获取定位失败");
								console.log("res", res)
							}
						});
					} else {
						fenseLongitude = this.longitude;
						fenseLatitude = this.latitude;
						this.saveFenceAPIFun(fenseLongitude, fenseLatitude);
					}

				}

			},
			saveFenceAPIFun(fenseLongitude, fenseLatitude) {
				saveFenceAPI({
					radius: this.raduis * 1000,
					longitude: fenseLongitude,
					latitude: fenseLatitude,
					carId: this.deviceData.id
				}).then(([err, data]) => {
					if (err) return;
					getCarDetailAPI(this.deviceData.id).then(([err, data]) => {
						if (err) return;
						//主要要获取到围栏的ID
						this.$store.commit("setMapDataPoint", {
							...this.mapDataPoint,
							isCrossFence: data.isCrossFence
						})
						this.$store.commit("setDeviceData", {
							...this.deviceData,
							carElectronicFence: data.carElectronicFence
						})
						this.updateFense();
					})
				})
			},
			closeFenceFun() {
				closeFenceAPI({
					ids: this.deviceData.carElectronicFence.id
				}).then(([err, data]) => {
					if (err) return;
					this.circles = [{
						radius: 0.5,
						longitude: -1,
						latitude: -1
					}];
					this.deviceData.carElectronicFence = {};
					this.$store.commit("setDeviceData", this.deviceData);
				})
			}
		}
	}
</script>

<style scoped>
	page {
		width: 100%;
		height: 100%;
	}

	.right-operate {
		position: fixed;
		right: 30upx;
		top: 30upx;
		/* top: 100upx; */
		background-color: #ffffff;
		opacity: 0.8;
		border-radius: 10upx;
		padding: 20upx 14upx;
	}

	.right-operate .item {
		margin-top: 20upx;
	}

	.border-operate-wrapper {
		position: fixed;
		bottom: 30upx;
		width: 100%;
		/* bottom: 120upx; */
		bottom: 30upx;
	}

	.border-operate {
		background-color: #fff;
		opacity: 0.95;
		border-radius: 20upx;
		padding: 20upx 30upx;

	}

	.refresh {
		animation: rotate 1s linear 1;
	}

	.pausedRfresh {
		animation-play-state: paused;
	}

	.runRefresh {
		animation-play-state: running;
	}

	@keyframes rotate {
		0% {
			transform: rotate(0deg);
		}

		25% {
			transform: rotate(90deg);
		}

		50% {
			transform: rotate(180deg);
		}

		75% {
			transform: rotate(270deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>
